package com.ms.qw.jsf.converter;

import com.ms.qw.application.mappers.CampanaMapper;
import com.ms.qw.client.dto.CampanaDTO;
import com.ms.qw.domain.model.CampanaRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;

/**
 * User: aglwkrs
 * Date: 30/11/11
 */
@Component
@FacesConverter("com.ms.qw.jsf.converter.ManagerCampanaDTOConverter")
public class ManagerCampanaDTOConverter implements Converter {

    @Autowired
    protected CampanaRepository campanaRepository;


    public Object getAsObject(FacesContext context, UIComponent component, String value) throws ConverterException {
        if (StringUtils.isBlank(value) || value.equals("Seleccione") || value.equals("Todos") ||
                value.equals("null"))
        {
            return null;
        }
        CampanaDTO result= campanaRepository.findById(Integer.parseInt(value));
        return result;
    }

    public String getAsString(FacesContext context, UIComponent component, Object value) throws ConverterException {
        if (value == null || !(value instanceof CampanaDTO)) {
            return null;
        }
        return String.valueOf(((CampanaDTO) value).getCodigo());
    }


}
